package com.quyunshuo.module.home.activity.main

import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import com.quyunshuo.edwinmusictwo.base.BaseApplication
import com.quyunshuo.edwinmusictwo.base.mvvm.vm.BaseViewModel
import com.quyunshuo.module.home.music.Music
import com.quyunshuo.module.home.music.MusicPlayer
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 首页的VM层
 *
 * @property mRepository HomeRepository 仓库层 通过Hilt注入
 *
 * @author Qu Yunshuo
 * @since 5/25/21 5:41 PM
 */
@HiltViewModel
class SharedViewModel @Inject constructor(private val mRepository: HomeRepository) :
    BaseViewModel() {
    private val _localMusic = MutableStateFlow<List<Music>>(emptyList())
    var localMusic = _localMusic.asStateFlow()

    fun loadMusic(context: Context) {
        viewModelScope.launch(Dispatchers.IO) {
            //使用协程在后台线程加载音乐
            val musicList = MusicPlayer.loadMusic(context)
            _localMusic.value = musicList
        }

    }


    private val _currentMusic = MutableStateFlow<Music?>(null)
    val currentMusic get() = _currentMusic.asStateFlow()

    private val _isPlaying = MutableStateFlow(false)
    val isPlaying get() = _isPlaying.asStateFlow()

    private val _progress = MutableStateFlow<Pair<Int, Int>?>(null)
    val progress get() = _progress.asStateFlow()

    fun setCurrentMusic(music: Music?) {
        _currentMusic.value = music
        //保存播放歌曲
        music?.let { addLatelyMusic(it) }

    }

    fun setIsPlaying(playing: Boolean) {
        _isPlaying.value = playing
    }

    fun setProgress(current: Int, total: Int) {
        _progress.value = Pair(current, total)
    }

    fun addLatelyMusic(music:Music){
        viewModelScope.launch {
            //查询，是否存在这首歌曲，如果存在，需要更新他的时间。
            mRepository.addLatelyMusic(music)
        }
    }

    fun getLatelyMusic()=mRepository.getLatelyMusic()

}
